package com.tian.auto.parse;

import com.tian.auto.Constants;
import com.tian.auto.Log;
import com.tian.auto.StringUtils;
import com.tian.auto.info.PathBean;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.tian.auto.Constants.PROJECT_STRING_PATH_MAP;

/**
 * 地址分析器
 */
public class PathParseProcessor {

    private final static String TAG = PathParseProcessor.class.getSimpleName();

    /**
     * 新添加的
     */
    private final static String[] newInsertLanguage = new String[]{"values-th-rTH"};

    /**
     * 加载到的项目下的 values目录，用module*res*values做键名，string开头或array开头的xml文件集合做值时 map键的分隔符
     */
    private final static String KEY_SEPARATOR = "*";

    /**
     * excel表中 moduleName的分割，如 "calm-app-main*printer_server_hint"
     */
    public final static String MODULE_NAME_SEPARATOR = "\\*";

    /**
     * 字符数组的分割符 如 "calm-app-main*card_type^item1"
     */
    public final static String STRING_ARRAY_SEPARATOR = "\\^item";

    //    //根目录
    private static String rootPath = "/Users/tianjinyong/Desktop/work/keruyun_calm3";
    //根目录
//    private final static String rootPath = "/Users/tianjinyong/Desktop/work/international";

    /**
     * 初始化
     *
     * @param root
     */
    public static void initProjectStringPathMap(String root) {
        rootPath = root;
        initProjectStringPathMap();
    }

    /**
     * 初始化，寻找module-src-main-res 的目录下的string-xxx.xml文件集合
     */
    public static void initProjectStringPathMap() {

        if (StringUtils.isEmpty(rootPath)) {
            return;
        }

        PROJECT_STRING_PATH_MAP.clear();
        File file = new File(rootPath);
        if (!file.exists() || !file.isDirectory()) {
            Log.info(TAG, "rootPath = " + rootPath + "配置不对");
            return;
        }
        for (File child : file.listFiles()) {
            if (!child.isDirectory())
                continue;

            File mainDir = new File(child.getAbsolutePath() + File.separator + "src" + File.separator + "main");

            if (mainDir.exists() && mainDir.isDirectory()) {

                for (File resDir : mainDir.listFiles()) {
                    //是res 开头的文件夹
                    if (!resDir.getName().startsWith("res") || !resDir.isDirectory())
                        continue;
                    newInsertLanguage(resDir);
                    //遍历下面的values开头的目录
                    for (File valuesDir : resDir.listFiles()) {
                        if (!valuesDir.getName().startsWith("values") || !valuesDir.isDirectory())
                            continue;
                        if (valuesDir.listFiles().length > 0) {
                            for (File stringFile : valuesDir.listFiles()) {
                                //需要遍历 values下所有 xml文件
                                if (!stringFile.getName().endsWith(".xml"))
                                    continue;
                                insertData(child.getName(), resDir.getName(), valuesDir.getName(), stringFile.getAbsolutePath());
                            }
                        } else {
                            insertData(child.getName(), resDir.getName(), valuesDir.getName(), "");
                        }
                    }
                }
            }

        }

        Log.info(TAG, PROJECT_STRING_PATH_MAP.toString());
    }

    /**
     * 在当前res下添加 新的语言环境
     */
    private static void newInsertLanguage(File resDir) {
        File[] files = resDir.listFiles();
        if (files == null || files.length == 0)
            return;
        for (String newInsertLanguage : newInsertLanguage) {
            //是否已经创建了 对于的目录
            boolean isAlreadyCreate = false;

            for (File file : files) {
                if (file.getName().equals(newInsertLanguage) && file.isDirectory()) {
                    isAlreadyCreate = true;
                    break;
                }
            }

            //如果没有需要新建
            if (!isAlreadyCreate) {
                File targetFile = new File(resDir, newInsertLanguage);
                targetFile.mkdirs();
            }
        }
    }

    /**
     * 向map中 插入数据
     *
     * @param moduleName
     * @param resDirName
     * @param valuesDirName
     * @param stringXmlPath
     */
    private static void insertData(String moduleName, String resDirName, String valuesDirName, String stringXmlPath) {
        //生成key
        String key = moduleName + KEY_SEPARATOR + resDirName + KEY_SEPARATOR + valuesDirName;
        if (!PROJECT_STRING_PATH_MAP.containsKey(key)) {
            PathBean pb = new PathBean();
            pb.setModuleName(moduleName);
            pb.setResDir(resDirName);
            pb.setValueDir(valuesDirName);

            List<String> stingXmlList = new ArrayList<>();
            stingXmlList.add(stringXmlPath);
            pb.setStringXmlFiles(stingXmlList);

            PROJECT_STRING_PATH_MAP.put(key, pb);
        } else {
            PathBean pb = PROJECT_STRING_PATH_MAP.get(key);
            pb.getStringXmlFiles().add(stringXmlPath);
        }
    }

    /**
     * 解析路径得到map表，便于取moduleName 和 string 的keyName 和 string-array的keyName
     *
     * @param path
     */
    public static HashMap<String, String> analysisPath(String path) {
        HashMap<String, String> map = new HashMap<>();
        String[] strs = path.split(MODULE_NAME_SEPARATOR);

        if (strs.length < 2) {
            Log.info(TAG, "path =" + path + "格式不正确");
            return map;
        }
        map.put(Constants.MapKey.MODULE_NAME, strs[0]);
        map.put(Constants.MapKey.KEY_NAME, strs[1]);

        String[] temps = strs[1].split(STRING_ARRAY_SEPARATOR);
        if (temps.length == 2) {
            map.put(Constants.MapKey.KEY_NAME, temps[0]);
            map.put(Constants.MapKey.ARRAY_INDEX, temps[1]);
        }
        return map;
    }


    /**
     * 根据module名 获取字典中的 string_xxx.xml集合数据
     *
     * @param moduleName
     * @param isNeedMatchModuleName 是否需要匹配 "moduleName",在"离线app下"不能去匹配moduleName因为modele名和文档的对不上
     * @return
     */
    public static HashMap<String, List<String>> getModuleList(String moduleName, boolean isNeedMatchModuleName) {
        HashMap<String, List<String>> moduleNameMap = new HashMap<>();

        if (!isNeedMatchModuleName) {
            for (String item : PROJECT_STRING_PATH_MAP.keySet()) {

                PathBean itemPb = PROJECT_STRING_PATH_MAP.get(item);

                if (moduleNameMap.containsKey(itemPb.getValueDir())) {
                    moduleNameMap.get(itemPb.getValueDir()).addAll(itemPb.getStringXmlFiles());
                } else {
                    List<String> tmp = new ArrayList<>();
                    tmp.addAll(itemPb.getStringXmlFiles());
                    moduleNameMap.put(itemPb.getValueDir(), tmp);
                }
            }

            return moduleNameMap;
        }

        for (String item : PROJECT_STRING_PATH_MAP.keySet()) {
            String[] tt = item.split(MODULE_NAME_SEPARATOR);
            if (tt[0].equals(moduleName)) {

                PathBean itemPb = PROJECT_STRING_PATH_MAP.get(item);

                if (moduleNameMap.containsKey(itemPb.getValueDir())) {
                    moduleNameMap.get(itemPb.getValueDir()).addAll(itemPb.getStringXmlFiles());
                } else {
                    List<String> tmp = new ArrayList<>();
                    tmp.addAll(itemPb.getStringXmlFiles());
                    moduleNameMap.put(itemPb.getValueDir(), tmp);
                }
            }
        }

        return moduleNameMap;
    }

}
